<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Libraries\Error;
use App\Models\AttendanceGroup;
use App\Models\Employee;
use App\Models\User;
use App\Models\WorkAttendanceMonth;
use App\Models\WorkAttendanceMonthRecord;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;

class WorkAttendanceMonthController extends ApiController
{


    public function create(Request $request) {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $uid = $userInfo['uid'];
        $user = User::where('uid',$uid)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];


        if ( $request->id) {
            $work_attendance_month = WorkAttendanceMonth::findOrFail($request->id);
            $work_attendance_month->mtime = time();
        } else {
            $work_attendance_month = new WorkAttendanceMonth();
            $work_attendance_month->ctime = time();
        }
        $work_attendance_month->employee_id = $request->employee_id;
        $employee = Employee::where('employee_id',$request->employee_id)->where('company_id',$company_id)->where('status',1)->first();

        $work_attendance_month->company_id = $company_id;
        $work_attendance_month->name = $employee['name'];
        $work_attendance_month->organization_id = $employee['organization_id'];

        $work_attendance_month->month = $request->month;
        $work_attendance_month->attendance_days = $request->attendance_days;
        $work_attendance_month->attendance_hours = $request->attendance_hours;
        $work_attendance_month->real_attendance_days = $request->real_attendance_days;
        $work_attendance_month->late_minutes = $request->late_minutes;
        $work_attendance_month->late_times = $request->late_times;
        $work_attendance_month->leave_early_minutes = $request->leave_early_minutes;
        $work_attendance_month->leave_early_times = $request->leave_early_times;
        $work_attendance_month->absenteeism_days = $request->absenteeism_days;
        $work_attendance_month->lack_card_times = $request->lack_card_times;
        $work_attendance_month->legal_holiday_days = $request->legal_holiday_days;
        $work_attendance_month->field_clock_in_days = $request->field_clock_in_days;
        $work_attendance_month->total_overtime = $request->total_overtime;
        $work_attendance_month->subsidy = $request->subsidy;
        $work_attendance_month->remark = $request->remark;
        $work_attendance_month->uid = $uid;

        $work_attendance_month->save();

        return showError(Error::ERR_OK,['id'=>$work_attendance_month->id]);

    }

    public function show(Request $request) {
        $work_attendance_month = WorkAttendanceMonth::findOrFail($request->id);
        return showError(Error::ERR_OK,['work_attendance_month'=>$work_attendance_month]);
    }

    public function index(Request $request)
    {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $uid = $userInfo['uid'];
        $user = User::where('uid',$uid)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];
        // 搜索内容
        $where = [];
        $name = $request->input('name');
        if (!empty($name))
        {
            $where['name'] = $name;
        }

        $organization_id = $request->input('organization_id');
        if (!empty($organization_id))
        {
            $where['organization_id'] = explode(",",$organization_id);
        }

        $month = $request->input('month');
        if (!empty($month))
        {
            $where['month'] = $month;
        }
        $where['company_id'] = $company_id;
        $where['status'] = 1;

        $list = WorkAttendanceMonth::getList($where);
        foreach ($list as $k => &$v) {

            $v->employee_info = Employee::where('employee_id',$v->employee_id)->where('company_id',$company_id)->where('status',1)->first();
        }
        return showError(Error::ERR_OK,['list'=>$list]);
    }

    public function delete(Request $request) {
        WorkAttendanceMonth::where('id',$request->id)->update(['status'=>2,'mtime'=>time()]);
        return showError(Error::ERR_OK);
    }

    public function stat(Request $request) {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $uid = $userInfo['uid'];
        $user = User::where('uid',$uid)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];

        $month = $request->month;
        $year = date('Y',strtotime($month));
        $monthnew = date('m',strtotime($month));
        $howdays = date("t",strtotime($month));

        $days = $this->workDays($year,$monthnew);

        $hours = $days*8;

        //根据公司名取所有人
        $employees = Employee::where('company_id',$company_id)->where('status',1)->get();
        foreach ($employees as $k=>$e) {
            $monthE = WorkAttendanceMonth::where('employee_id',$e->employee_id)->where('month',$month)->first();
            if (!empty($monthE)) {
                $work_attendance_month = WorkAttendanceMonth::findOrFail($monthE->id);
                $work_attendance_month->mtime = time();
            } else {
                $work_attendance_month = new WorkAttendanceMonth();
                $work_attendance_month->ctime = time();
            }
            $work_attendance_month->employee_id = $e->employee_id;
            $work_attendance_month->company_id = $company_id;
            $work_attendance_month->name = $e->name;
            $work_attendance_month->organization_id = $e->organization_id;
            $work_attendance_month->month = $month;
            $work_attendance_month->attendance_days = $days;
            $work_attendance_month->attendance_hours = $hours;


            //每个都需要算一下
            $real_attendance_days = 0;
            $late_minutes = 0;
            $late_times = 0;
            $leave_early_minutes = 0;
            $leave_early_times = 0;
            $absenteeism_days = 0;
            $lack_card_times = 0;
            $attendance_records = WorkAttendanceMonthRecord::where('employee_id',$e->employee_id)->where("company_id",$company_id)->where("month",$month)->where("status",1)->first();
            $attendance_group = AttendanceGroup::where('company_id',$company_id)->where('status',1)->first();

            for($i=1;$i<=$howdays;$i++) {
                $t=mktime(0,0,0,$monthnew,$i,$year);
                $week=date('w',$t);//每号的星期数

                if ($week >0 && $week<6) {

                    switch ($week)
                    {
                        case 0:
                            $key = 'ag_sun';
                            break;
                        case 1:
                            $key = 'ag_mon';
                            break;
                        case 2:
                            $key = 'ag_tue';
                            break;
                        case 3:
                            $key = 'ag_wed';
                            break;
                        case 4:
                            $key = 'ag_thu';
                            break;
                        case 5:
                            $key = 'ag_fri';
                            break;
                        case 6:
                            $key = 'ag_sat';
                            break;

                    }
                    $clock_time = $attendance_group[$key];
                    $clock_time = str_replace("早晚 ","",$clock_time);
                    $clock_time = str_replace(";","",$clock_time);
                    $clock_time = explode("~",$clock_time);
                    $start_time = $clock_time[0];
                    $end_time = $clock_time[1];

                    $dayNmorning = "day".$i."_morning";
                    $dayNmorningstatus = "day".$i."_morning_status";
                    $dayNnight = "day".$i."_night";
                    $dayNnightstatus = "day".$i."_night_status";
                    if(empty($attendance_records->$dayNmorning) && empty($attendance_records->$dayNnight) ) {
                        $absenteeism_days += 1;
                    } else {
                        $real_attendance_days +=1;
                    }
                    if (isset($attendance_records->$dayNmorningstatus) && $attendance_records->$dayNmorningstatus==2) {
                        $late_times +=1;
                        $late_minutes += (strtotime(date('H:i:s',$attendance_records->$dayNmorning))-strtotime($start_time))/60;
                    }
                    if (isset($attendance_records->$dayNnightstatus) && $attendance_records->$dayNnightstatus==2) {
                        $leave_early_times +=1;
                        $leave_early_minutes += (strtotime($end_time)-strtotime(date('H:i:s',$attendance_records->$dayNnight)))/60;
                    }
                }

            }

            $work_attendance_month->real_attendance_days = $real_attendance_days;
            $work_attendance_month->late_minutes = $late_minutes;
            $work_attendance_month->late_times = $late_times;
            $work_attendance_month->leave_early_minutes = $leave_early_minutes;
            $work_attendance_month->leave_early_times = $leave_early_times;
            $work_attendance_month->absenteeism_days = $absenteeism_days;
            $work_attendance_month->lack_card_times = $lack_card_times;


            $work_attendance_month->save();
        }

        return showError(Error::ERR_OK);

    }


    private function workDays($year,$month){
        $day=1;
        $days=0;
        $t=mktime(0,0,0,$month,$day,$year);
        $days=date('t',$t);
        $fristDayWeek=date('w',$t);//每月一号的星期数
        $lastDayWeek=date('w',mktime(0,0,0,$month,$days,$year));//每月最后一天的星期数
        if($days>28){//非平年二月算法，平年二月无论怎么都只有20天。
            if($fristDayWeek==6)//起始日是星期六的减去2天，星期天的减去一天。
                $days-=2;
            if($fristDayWeek==0)
                $days-=1;
            if($lastDayWeek==6)//结束日是星期六的减去一天，星期天的减去2天。
                $days-=1;
            if($lastDayWeek==0)
                $days-=2;
        }

        if($days<28)//每个月最少会工作20天，此处修正开始日期是星期六，结束日期是星期天的31天的月份

            $days=28;
        return $days-8;// 减去每个月都有的4个星期天共8天
    }
}
